﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace XYZshell.Game.CardGameEngine
{
	/// <summary>
	/// 逻辑条件
	/// </summary>
	[Condition("logic")]
	public  class LogicCodition:BaseCondition
	{
		/// <summary>
		/// 逻辑类型
		/// </summary>
		public LogicType LogicType
		{
			get;
			set;
		}
		/// <summary>
		/// 条件表达式1
		/// </summary>
		public BaseCondition Condition1
		{
			get;
			set;
		}
		/// <summary>
		/// 条件表达式2
		/// </summary>
		public BaseCondition Condition2
		{
			get;
			set;
		}
		/// <summary>
		/// 计算条件表达式的结果
		/// </summary>
		/// <returns>条件表达式的结果</returns>
		public override bool Result()
		{
			switch (this.LogicType)
			{
				case LogicType.AND:
					return this.Condition1.Result()&&this.Condition2.Result();
				case LogicType.OR:
					return this.Condition1.Result() || this.Condition2.Result();
				case LogicType.NOT:
					return !this.Condition1.Result();
					
			}
			return false;
		}

		/// <summary>
		/// 获得逻辑表达式的XML内容
		/// </summary>
		/// <returns></returns>
		public override string GetXMLContent()
		{
			StringBuilder sb=new StringBuilder();

			sb.AppendFormat( "<logic type=\"{0}\">\r\n" ,this.LogicType);
			sb.Append( Condition1.ToXML() );
			if (this.LogicType!=LogicType.NOT)
			{
				sb.Append( Condition2.ToXML() );
			}
			sb.AppendLine( "</logic>" );
			return sb.ToString();
		}
		/// <summary>
		/// 从XML中生成逻辑条件
		/// </summary>
		/// <param name="xmlnode">XML内容</param>
		/// <returns>逻辑条件</returns>
		public static  LogicCodition FromXML( string xmlnode )
		{	
			LogicCodition rtn=new LogicCodition();
			XObject xo=new XObject( xmlnode );
			XObject logic= xo.Childs[0];
			XObject cond1=logic.Child( "condition", true );
			
			rtn.LogicType = (LogicType)Enum.Parse( typeof( LogicType), logic.Type, true );
			rtn.Condition1 = BaseCondition.FromXML( cond1.OuterXml );
			if (rtn.LogicType != LogicType.NOT)
			{
				XObject cond2=cond1.NextSame;
				rtn.Condition2 = BaseCondition.FromXML( cond2.OuterXml );
			}
			return rtn;
		}
	}
}
